package com.color.admin.common.security.service;

import com.color.admin.common.core.base.AuthUser;
import com.color.admin.common.security.entity.SecurityUser;
import com.color.admin.system.entity.SysUser;
import com.color.admin.system.servie.MenuService;
import com.color.admin.system.servie.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author HaiQiu
 * @date 2022/2/21
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userService.loadUserByUsername(username);
        if (ObjectUtils.isEmpty(sysUser)){
            throw new UsernameNotFoundException("用户不存在");
        }
        List<AuthUser> authUsers = menuService.authList(sysUser.getId());
        if (CollectionUtils.isEmpty(authUsers)){
            throw new BadCredentialsException("用户无匹配权限");
        }
        Set<GrantedAuthority> authorities = authUsers.stream().map(authUser ->
                new SimpleGrantedAuthority(authUser.getPath())).collect(Collectors.toSet());
        SecurityUser user = new SecurityUser(sysUser.getUsername(),sysUser.getPassword(),
                sysUser.getActive(),sysUser.getActive(),sysUser.getActive(),sysUser.getActive(),authorities);
        return user;
    }
}
